const WebSocket = require('ws');
const fileUtils = require('./fileUtils');
const dataGenerator = require('./dataGenerator');

// 创建WebSocket服务器
function createWebSocketServer(server) {
    const wss = new WebSocket.Server({ server });

    // WebSocket连接处理
    wss.on('connection', (ws) => {
        console.log('WebSocket客户端已连接');

        // 处理客户端消息
        ws.on('message', async (message) => {
            try {
                const data = JSON.parse(message);

                if (data.type === 'subscribe') {
                    console.log('客户端订阅频道:', data.channels);
                    ws.channels = data.channels;
                } else if (data.type === 'refresh_all') {
                    console.log('客户端请求刷新所有数据');
                    await broadcastUpdatedData(wss);
                } else if (data.type === 'alarm_handled') {
                    console.log('客户端处理了预警:', data.id);
                    // 这里可以添加预警处理逻辑
                }
            } catch (error) {
                console.error('处理WebSocket消息失败:', error);
            }
        });

        // 连接关闭
        ws.on('close', () => {
            console.log('WebSocket客户端已断开连接');
        });

        // 发送初始数据
        sendInitialData(ws);
    });

    return wss;
}

// 向客户端发送初始数据
async function sendInitialData(ws) {
    try {
        const [
            airQuality,
            pollutionRanking,
            temperatureHumidity,
            waterQuality,
            energyConsumption,
            monitoringStations,
            overviewStats
        ] = await Promise.all([
            fileUtils.readDataFile('airQuality'),
            fileUtils.readDataFile('pollutionRanking'),
            fileUtils.readDataFile('temperatureHumidity'),
            fileUtils.readDataFile('waterQuality'),
            fileUtils.readDataFile('energyConsumption'),
            fileUtils.readDataFile('monitoringStations'),
            fileUtils.readDataFile('overviewStats')
        ]);

        ws.send(JSON.stringify({ type: 'air_quality', data: airQuality }));
        ws.send(JSON.stringify({ type: 'pollution_ranking', data: pollutionRanking }));
        ws.send(JSON.stringify({ type: 'temperature_humidity', data: temperatureHumidity }));
        ws.send(JSON.stringify({ type: 'water_quality', data: waterQuality }));
        ws.send(JSON.stringify({ type: 'energy_consumption', data: energyConsumption }));
        ws.send(JSON.stringify({ type: 'monitoring_stations', data: monitoringStations }));
        ws.send(JSON.stringify({ type: 'overview_stats', data: overviewStats }));
    } catch (error) {
        console.error('发送初始数据失败:', error);
    }
}

// 更新数据文件
async function updateDataFile(fileKey) {
    try {
        const generator = dataGenerator.generators[fileKey];
        if (!generator) {
            throw new Error(`未找到数据生成器: ${fileKey}`);
        }

        const newData = generator();
        await fileUtils.writeDataFile(fileKey, newData);
        return newData;
    } catch (error) {
        console.error(`更新数据文件失败 ${fileKey}:`, error);
        throw error;
    }
}

// 广播更新的数据给所有客户端
async function broadcastUpdatedData(wss) {
    try {
        // 更新所有数据文件
        const [
            airQuality,
            pollutionRanking,
            temperatureHumidity,
            waterQuality,
            energyConsumption,
            monitoringStations,
            overviewStats
        ] = await Promise.all([
            updateDataFile('airQuality'),
            updateDataFile('pollutionRanking'),
            updateDataFile('temperatureHumidity'),
            updateDataFile('waterQuality'),
            updateDataFile('energyConsumption'),
            updateDataFile('monitoringStations'),
            updateDataFile('overviewStats')
        ]);

        // 广播给所有连接的客户端
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify({ type: 'air_quality', data: airQuality }));
                client.send(JSON.stringify({ type: 'pollution_ranking', data: pollutionRanking }));
                client.send(JSON.stringify({ type: 'temperature_humidity', data: temperatureHumidity }));
                client.send(JSON.stringify({ type: 'water_quality', data: waterQuality }));
                client.send(JSON.stringify({ type: 'energy_consumption', data: energyConsumption }));
                client.send(JSON.stringify({ type: 'monitoring_stations', data: monitoringStations }));
                client.send(JSON.stringify({ type: 'overview_stats', data: overviewStats }));
            }
        });

        return {
            airQuality,
            pollutionRanking,
            temperatureHumidity,
            waterQuality,
            energyConsumption,
            monitoringStations,
            overviewStats
        };
    } catch (error) {
        console.error('广播更新数据失败:', error);
        throw error;
    }
}

// 广播单个数据类型更新
async function broadcastSingleUpdate(wss, dataType) {
    try {
        const fileKey = dataTypeToFileKey(dataType);
        if (!fileKey) {
            throw new Error(`无效的数据类型: ${dataType}`);
        }

        const updatedData = await updateDataFile(fileKey);

        // 广播给所有连接的客户端
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify({ type: dataType, data: updatedData }));
            }
        });

        return updatedData;
    } catch (error) {
        console.error(`广播${dataType}更新失败:`, error);
        throw error;
    }
}

// 广播预警信息
function broadcastAlarm(wss) {
    try {
        const alarm = dataGenerator.generateAlarmData();

        // 广播给所有连接的客户端
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify({ type: 'alarm', data: alarm }));
            }
        });

        console.log('已发送预警信息:', alarm.title);
        return alarm;
    } catch (error) {
        console.error('广播预警信息失败:', error);
        throw error;
    }
}

// 辅助函数：将数据类型转换为文件键
function dataTypeToFileKey(dataType) {
    const mapping = {
        'air_quality': 'airQuality',
        'pollution_ranking': 'pollutionRanking',
        'temperature_humidity': 'temperatureHumidity',
        'water_quality': 'waterQuality',
        'energy_consumption': 'energyConsumption',
        'monitoring_stations': 'monitoringStations',
        'overview_stats': 'overviewStats'
    };

    return mapping[dataType] || null;
}

module.exports = {
    createWebSocketServer,
    sendInitialData,
    updateDataFile,
    broadcastUpdatedData,
    broadcastSingleUpdate,
    broadcastAlarm
};